package com.gec.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
public class ApplicationConfig {

    //通过spring容器注入DataSource
    @Autowired
    private DataSource dataSource;

    //创建PasswordEncoder对象
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //创建jdbcUserDetailsService对象
    @Bean
    public UserDetailsService userDetailsService() {
        System.out.println(dataSource);
        //初始化数据源 ---- jdbcTemplates对象
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);

        //声明用户,同时添加进数据库
        if (!manager.userExists("admin")) {

            manager.createUser(User.withUsername("admin")
                    .password(passwordEncoder().encode("admin"))
                    .roles("ADMIN", "USER", "MANAGER")
                    .build());
        }

        if (!manager.userExists("zs")) {

            manager.createUser(User.withUsername("zs")
                    .password(passwordEncoder().encode("123"))
                    .roles("USER")
                    .build());
        }

        if (!manager.userExists("lisi")) {

            manager.createUser(User.withUsername("lisi")
                    .password(passwordEncoder().encode("456"))
                    .roles("USER", "NORMAL")
                    .build());
        }

        return manager;
    }
}
